#!/bin/bash

CONFPATH="/etc/spindown.conf"
VARDIR="/var/run/spindown"
FIFOPATH="${VARDIR}/spindownd.fifo"
PIDFILE="${VARDIR}/spindownd.pid"

. /etc/rc.conf
. /etc/rc.d/functions

#prints table with status about the disks
status() {
    #print the header of the table
	printf "%-5s %10s %10s %15s %20s\n" name watched active idle-time spindown-time

	while read line; do

		printf "%-5s %10s %10s %15s %20s\n" $line

	done < ${FIFOPATH}

    exit 0
}

PID=$(pidof -o %PPID /sbin/spindownd)
case "$1" in
    start)
        stat_busy "Starting disk spindown daemon"
	[ ! -d ${VARDIR} ] && mkdir -p ${VARDIR} &> /dev/null
        [ -z "${PID}" ] && /sbin/spindownd -d -f ${FIFOPATH} -c ${CONFPATH} -p ${PIDFILE}
	if [ $? -gt 0 ]; then
		stat_fail
	else
		add_daemon spindown
		stat_done
	fi
	;;
    stop)
        stat_busy "Stopping disk spindown daemon"
        [ -f "${PIDFILE}" ] && kill $(cat ${PIDFILE}) &>/dev/null
	if [ $? -gt 0 ]; then
		stat_fail
	else
		rm_daemon spindown
		stat_done
	fi
	;;
    status)
    	[ -z "${PID}" ] && exit 1
	echo -n
	status &
	sleep 0.1
	kill -PIPE ${PID}
	wait $!
        ;;
    restart)
        $0 stop
	sleep 1
        $0 start
        ;;
    *)
        echo "usage: $0 {start|stop|restart|status}"
	;;
esac
exit 0
